//
//  FR_RankListViewController.m
//  FaceRecognition
//
//  Created by syun on 17/2/9.
//  Copyright © 2017年 Sylar. All rights reserved.
//

#import "FR_RankListViewController.h"
#import "rankListTableViewCell.h"
#import "DropTable.h"

@interface FR_RankListViewController ()<UITableViewDelegate,UITableViewDataSource,DropTableDelgate>
{
   DropTable * drop_table;
    
    UILabel * monthLabel;
    
    NSString * selectedCurrentMonth;
    
    UILabel * label;
    
    NSString * customStr;
    
    NSString * currentmonth;
    
    UILabel *markLabel;
}
@property (nonatomic, strong) UITableView * table;

@property (nonatomic, strong) NSMutableArray * monthArray;
@end

@implementation FR_RankListViewController

- (UITableView *)table
{
    if (_table == nil) {
        
        _table = [[UITableView alloc]initWithFrame:CGRectMake(0, 50.5+64, SCREENWIDTH, SCREENHEIGH-64-50.5) style:UITableViewStylePlain];
        _table.delegate = self;
        _table.dataSource = self;
        _table.scrollEnabled = NO;
        _table.separatorStyle = UITableViewCellSeparatorStyleNone;
        
    }
    
    return _table;
}
    
- (NSMutableArray *)rankArr
{
    if (_rankArr == nil) {
        
        _rankArr = [NSMutableArray array];
    }
    
    return _rankArr;
}

- (NSMutableArray *)monthArray
{
    if (_monthArray == nil) {
        
        _monthArray = [NSMutableArray array];
    }
    
    return _monthArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    selectedCurrentMonth = [self getCurrentMonthString];
    
    if (_flag == 1) {
        
       self.navBar.navigationItem.title = _CurrentClassName;
    }else
    {
       self.navBar.navigationItem.title = _CurrentSchoolName;
    }
    
    
    [self downMonth];
    
    [self.view addSubview:self.table];
    
    [self requestRankingData];
    
    // Do any additional setup after loading the view.
}


#pragma mark -DropTableDelegate
- (void)tableViewCellSelected:(NSInteger)index{
    
    selectedCurrentMonth = [self.monthArray objectAtIndex:index];
    [self getCustomData:selectedCurrentMonth];
    monthLabel.text = customStr;
    markLabel.text = [NSString stringWithFormat:@"%@月勤奋前五名",currentmonth];
    [self requestRankingData];
}
- (void)loadTopView
{
    markLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 16 +64, 200, 18)];
    markLabel.font = [UIFont systemFontOfSize:18];
    markLabel.textColor = DEFAULTCOLOR;
    
    NSString * monthStr = [self getCurrentMonthString];
    
    [self getCustomData:monthStr];
    
    markLabel.text = [NSString stringWithFormat:@"%@月勤奋前五名",currentmonth];
    [self.view addSubview:markLabel];
    
    UIView * monthBackView = [[UIView alloc]initWithFrame:CGRectMake(SCREENWIDTH-15-98, 12+64, 98, 26)];
    monthBackView.layer.cornerRadius = 5;
    monthBackView.layer.borderWidth = 0.5;
    monthBackView.layer.borderColor = DEFAULTCOLOR.CGColor;
    monthBackView.backgroundColor = [UIColor colorWithHexString:@"b1e7fc"];
    [self.view addSubview:monthBackView];
    
    monthLabel =[[UILabel alloc]initWithFrame:CGRectMake(6, 6, 75, 13)];
    
    NSString * monthstr = [self.monthArray objectAtIndex:0];
    [self getCustomData:monthstr];
    monthLabel.text = customStr;
    
    monthLabel.textColor = DEFAULTCOLOR;
    monthLabel.font = [UIFont systemFontOfSize:13];
    monthLabel.textAlignment = NSTextAlignmentCenter;
    [monthBackView addSubview:monthLabel];
    
    UIImageView * arrowImag =[[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(monthLabel.frame), 10, 11, 5)];
    arrowImag.image = [UIImage imageNamed:@"ranking_datechoice_"];
    [monthBackView addSubview:arrowImag];
    
    UIButton * monthButton = [UIButton buttonWithType:UIButtonTypeCustom];
    monthButton.frame = CGRectMake(SCREENWIDTH-15-98, 12+64, 98, 26);
    [monthButton addTarget:self action:@selector(chooseMonthAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:monthButton];
    
    UIView * line = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(markLabel.frame)+16, SCREENWIDTH, 0.5)];
    line.backgroundColor = [UIColor colorWithHexString:@"dedede"];
    [self.view addSubview:line];
}

- (void)chooseMonthAction:(UIButton *)sender
{
    drop_table = [[DropTable alloc] initWithView:sender];
    drop_table.lists = self.monthArray;
    drop_table.localtion = localtionTypeCustomRight;
    drop_table.delegate = self;
    drop_table.tableWidth = 120;
    drop_table.maginRight = 10;
    
}




- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self.rankArr count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 58;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 41;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * tBack = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 44)];
    
    UILabel * leftLable = [[UILabel alloc]initWithFrame:CGRectMake(0, 12, SCREENWIDTH/3, 16)];
    leftLable.textAlignment = NSTextAlignmentCenter;
    leftLable.text = @"用户头像";
    leftLable.textColor = [UIColor colorWithHexString:@"3b3b3b"];
    leftLable.font = [UIFont systemFontOfSize:16];
    [tBack addSubview:leftLable];
    
    UILabel * middleLable = [[UILabel alloc]initWithFrame:CGRectMake(SCREENWIDTH/3, 12, SCREENWIDTH/3, 16)];
    middleLable.textAlignment = NSTextAlignmentCenter;
    middleLable.text = @"姓名";
    middleLable.textColor = [UIColor colorWithHexString:@"3b3b3b"];
    middleLable.font = [UIFont systemFontOfSize:16];
    [tBack addSubview:middleLable];
    
    UILabel * rightLabel =  [[UILabel alloc]initWithFrame:CGRectMake(SCREENWIDTH/3*2, 12, SCREENWIDTH/3, 16)];
    rightLabel.textAlignment = NSTextAlignmentCenter;
    rightLabel.text = @"次数(时间段)";
    rightLabel.textColor = [UIColor colorWithHexString:@"3b3b3b"];
    rightLabel.font = [UIFont systemFontOfSize:16];
    [tBack addSubview:rightLabel];
    
    return tBack;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    rankListTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"rankListCell"];
    if (cell == nil) {
        
        cell = [[rankListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"rankListCell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    RankModel * model =[self.rankArr objectAtIndex:indexPath.row];
    cell.ranknumLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row +1];
    cell.nameLabel.text = model.username;
    cell.numLabel.text = [NSString stringWithFormat:@"%@次",model.arraycount];
    [cell.headImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",REQUESTIMAGEURL,model.logo]] placeholderImage:[UIImage imageNamed:@"personalsettings_switchloading_pic_"]];
    
    
    return cell;
    
}

-(void)downMonth
{
    RequestParam *param = [[RequestParam alloc] init];
    param.method = @"sy_rollcall_getmonth";
    
    [Utils get:nil parameters:param.mj_keyValues success:^(NSInteger recode, id jsonObject) {
        
        NSDictionary *dict = (NSDictionary *)jsonObject;
        NSArray * array = [dict objectForKey:@"re_data"];
        if (array.count > 0) {
            
            for (int i = 0 ; i< array.count; i++) {
                
                [self.monthArray addObject:[[array objectAtIndex:i] objectForKey:@"month"]];
                
            }
            
            [self loadTopView];
        }
        NSLog(@"%@",dict);
    } failure:^(NSInteger recode, NSError *error) {
        
        [self showHint:error.localizedDescription];
    }];
    
}
-(void)requestRankingData
{
    
    RequestParam *param = [[RequestParam alloc] init];
    if (_flag == 1) {
        
        param.classid = _classID;
        param.scid = [NSString stringWithFormat:@"%lld",[SYAccountTool ShareAccount].account.schoolManage];
    }else
    {
        param.scid = _schoolID;
        param.classid = @"0";
    }
    param.datetime = [NSString stringWithFormat:@"%@-01",selectedCurrentMonth];
    
    [Utils Java_get:@"api/getMonthCountTop" parameters:param.mj_keyValues success:^(NSInteger recode, id jsonObject) {
        
        NSArray *array = [jsonObject objectForKey:@"re_data"];
        NSLog(@"array = %@%@",array,jsonObject);
        
        [self.rankArr removeAllObjects];
        
        self.table.hidden = NO;
        label.hidden = YES;
        
        
        if (array.count>0) {
            
            for (NSDictionary * dic in array) {
                
                RankModel * model = [RankModel mj_objectWithKeyValues:dic];
                [self.rankArr addObject:model];
            }
            
            [self.table reloadData];
            
        }else
        {
            self.table.hidden = YES;
            label = [[UILabel alloc]initWithFrame:CGRectMake(0, SCREENHEIGH/2, SCREENWIDTH, 15)];
            label.text = @"暂无排名";
            label.font = [UIFont systemFontOfSize:15];
            label.textColor = RGBCOLOR(151, 151, 151);
            label.textAlignment = NSTextAlignmentCenter;
            [self.view addSubview:label];
        }
        
    } failure:^(NSInteger recode, NSError *error) {
        [self showHint:error.localizedDescription];
    }];
    
    /*
    RequestParam *param = [[RequestParam alloc] init];
    param.method = @"api_face_ranking";
    
    if (_flag == 1) {
        
           param.classid = _classID;
    }else {
           param.scid = _schoolID;
    }

    param.datetime = [NSString stringWithFormat:@"%@-01",selectedCurrentMonth];
    
    
    [Utils get:nil parameters:param.mj_keyValues success:^(NSInteger recode, id jsonObject) {
        
        NSArray *array = [jsonObject objectForKey:@"re_data"];
        NSLog(@"array = %@%@",array,jsonObject);
        
        [self.rankArr removeAllObjects];
        
        self.table.hidden = NO;
        label.hidden = YES;
        
        
        if (array.count>0) {
            
            for (NSDictionary * dic in array) {
                
                RankModel * model = [RankModel mj_objectWithKeyValues:dic];
                [self.rankArr addObject:model];
            }
            
            [self.table reloadData];
            
        }else
        {
            self.table.hidden = YES;
            label = [[UILabel alloc]initWithFrame:CGRectMake(0, SCREENHEIGH/2, SCREENWIDTH, 15)];
            label.text = @"暂无排名";
            label.font = [UIFont systemFontOfSize:15];
            label.textColor = RGBCOLOR(151, 151, 151);
            label.textAlignment = NSTextAlignmentCenter;
            [self.view addSubview:label];
        }
        
        
        
    } failure:^(NSInteger recode, NSError *error) {
        
        [self showHint:error.localizedDescription];
    }];
    */
}
- (NSString *)getCurrentMonthString
{
    NSCalendar *calender = [NSCalendar currentCalendar];//获取NSCalender单例。
    NSDateComponents *cmp = [calender components:(NSCalendarUnitMonth | NSCalendarUnitYear) fromDate:[NSDate date]]; //设置属性，因为我只需要年和月，这个属性还可以支持时，分，秒。
    NSDate *currentMonDate = [calender dateFromComponents:cmp];
    
    NSDateFormatter* formater = [[NSDateFormatter alloc] init];
    
    [formater setDateFormat:@"YYYY-MM"];
    
    NSString *month = [formater stringFromDate:currentMonDate];
    
    return month;
    
}

- (void)getCustomData :(NSString * )string
{
    
    
    NSString * monthstr = string;
    
    if (monthstr.length > 6) {
        
        NSString * year = [monthstr substringToIndex:4];
        
        NSString * month = [monthstr substringFromIndex:5];
        
        if (month.length > 1) {
            
            NSString * month2 = month;
            
            month2 = [month2 substringToIndex:1];
            
            if ([month2 isEqualToString:@"0"]) {
                
                month = [monthstr substringFromIndex:6];
            }
        }
        currentmonth = month;
        customStr = [NSString stringWithFormat:@"%@年%@月",year,month];
    }

}

- (void)viewWillDisappear:(BOOL)animated
{
    NSLog(@"self.rankArray = %@",self.rankArr);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
